import { defineStore } from 'pinia'
import { login, getUserInfoById, getUserMenusByRoleId } from '@/service/login'
import type { ILoginState } from '@/types'
import { localCache } from '@/utils/cache'
import router from '@/router'
// 模拟接口返回数据
import { menuList, user01Menus } from './testMenus'
import mapMenus from '@/utils/map-menus'

const useLoginStore = defineStore('login', {
  state: () => ({
    token: localCache.getCache('token') ?? '',
    name: localCache.getCache('name') ?? '',
    userInfo: localCache.getCache('userInfo') ?? {},
    userMenus: localCache.getCache('userMenus') ?? {}
  }),
  actions: {
    async loginAction(data: ILoginState) {
      if (data.name != 'admin' && data.name != 'user01') return
      // const loginRes: any = await login(data)
      // const id = loginRes.data?.id
      // this.name = loginRes.data?.name
      // this.token = loginRes.data?.token
      this.name = data.name
      this.token = 'testtoken'
      localCache.setCache('token', this.token)
      localCache.setCache('name', this.name)
      // 获取登录用户的信息
      // const userInfoRes: any = await getUserInfoById(id)
      // const userInfo = userInfoRes.data
      // this.userInfo = userInfo
      this.userInfo = data
      localCache.setCache('userInfo', this.userInfo)
      // 再获取登录用户的菜单路由
      // const menusRes: any = await getUserMenusByRoleId(userInfo.role.id)
      // this.userMenus = menusRes.data

      // 模拟数据代码
      if (data.name == 'admin') {
        this.userMenus = menuList
      } else if (data.name == 'user01') {
        this.userMenus = user01Menus
      }

      localCache.setCache('userMenus', this.userMenus)
      // 动态添加路由
      mapMenus(menuList)

      router.push('/main')
    },
    loadLocalCacheAction() {
      // 1.用户进行刷新默认加载数据
      const token = localCache.getCache('token')
      const userInfo = localCache.getCache('userInfo')
      const userMenus = localCache.getCache('userMenus')
      if (token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus
        // 2.动态添加路由
        mapMenus(userMenus)
      }
    }
  }
})

export default useLoginStore
